package com.cs.pk.codestriker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.cs.pk.utils.ClearCaseException;
import com.cs.pk.utils.UtilRepository;

public class GetLatestDesc extends AbstractPopulateList{

	private String sPath,vDir=null;
	private ArrayList fileDiff = new ArrayList();
	private String fileVersions[] =null;
	int number = 0;
	private String fileName = null;
	private String[] parentElement = null;
	private String parentPath = "";
	
	public GetLatestDesc(String streamPath, String viewDir) {
		super(null);
		sPath = streamPath;
		vDir = viewDir;
	}

	protected String filterOutput() {
		if(result!=null) {
			return result.trim();
		}
		return result;
	}

	
	protected void populate(Object payload) throws IOException,
			InterruptedException {
		parentPath ="";
		String variables[] = (String[])payload;
		fileVersions = new String[2];
		fileVersions[0]= variables[0]+"@@"+variables[1];
		fileName = variables[0];
		parentElement = variables[1].trim().split("\\\\");
        
		if(!process4Desc("...\\"+sPath+"\\LATEST")) {
			parentPath = sPath;
			process4Desc(createPath(number)+parentPath+"LATEST");
		}
       fileDiff.add(fileVersions);		
	}
	

	private boolean process4Desc(String streamPath) throws IOException, InterruptedException {
		number++;
		String output = null;
		try {
			output = runBatFile(new String[] {UtilRepository.DRIVE+":","cd "+vDir ,"cleartool desc -fmt %Vn -ver "+streamPath+" "+fileName});
			fileVersions[1] = fileName+"@@"+output;
			return true;
		} catch (ClearCaseException e) {
			if(number<parentElement.length) {
					process4Desc(createPath(number)+parentPath+"LATEST");
			}			
		}
		return false;
	}
	
	private String createPath(int i) {
		String path = "";
		for (int j = 0; j <=i; j++) {
			path = "\\"+parentElement[j]+"\\";
		}
		return path;
	}

	public void clear() {}

	public List getFileListForDifference() {
		return fileDiff;
	}
	
}
